package com.matrix.draft.zookeepertest;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessLock;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;

import java.util.concurrent.TimeUnit;

public class Train12306 {
    private CuratorFramework zkClient = null;

    public Train12306() {
        // 建立连接
        zkClient = CuratorFrameworkFactory.builder()
                .connectString("127.0.0.1:2181")
                .sessionTimeoutMs(60 * 1000)
                .connectionTimeoutMs(15 * 1000)
                .retryPolicy(new ExponentialBackoffRetry(3000, 10))
                .namespace("test") // 不用每次操作都要加上项目名, 他会自动加
                .build();
        zkClient.start();
        System.out.println("客户端" + zkClient + "已连接成功");
    }

    public int getTicket(String tickId) {
        // new InterProcessMutex锁对象, 传入一个path, 准备将某一张票锁住
        InterProcessLock lock = new InterProcessMutex(zkClient, "/lock/" + tickId);
        try {
            // 获取锁
            lock.acquire(3, TimeUnit.SECONDS); // 3秒还没获取到锁就报错
            // 开始业务
            return Train12306DB.tickets <= 0 ? -1 : Train12306DB.tickets--;
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        } finally {
            // 释放锁
            try {
                lock.release();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
